﻿using SolidWorks.Interop.sldworks;
using System;
using NCalc;
using System.Collections.Generic;
using SolidWorks.Interop.swconst;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SwParaPlatform2.logger;

namespace SwParaPlatform2.tools
{
    public class CommonTools
    {
        private CommonTools() { }
        private static readonly CommonTools _instance = new CommonTools();
        public static CommonTools Instance => _instance;
        public static Dictionary<string, string> GetFileNamePathDictionary(List<string> solidWorksFiles)
        {
            // 注意：如果可能存在同名文件，可以考虑如何处理重复键
            return solidWorksFiles.ToDictionary(Path.GetFileName, filePath => filePath);
        } //工具
        public static string ReadPathFromFile()
        {
            string filePath = @"D:\PATH.txt";

            if (!File.Exists(filePath))
                throw new FileNotFoundException("路径文件不存在：", filePath);

            string content = File.ReadAllText(filePath).Trim();//读取指定路径文件

            if (string.IsNullOrWhiteSpace(content))//检测内容是否为空
                throw new InvalidDataException("路径文件为空或只包含空白字符。");

            return content;
        }
        public static List<string> GetFileNames(List<string> solidWorksFiles)
        {
            return solidWorksFiles
                .Select(Path.GetFileName)
                .Where(name => !name.StartsWith("~$"))
                .ToList();
        }//工具
        public static Dictionary<string, object> ConvertDriveDataUnits(
             Dictionary<string, object> driveData,
             Dictionary<string, Dictionary<string, object>> dUIConfigData)
        {
            var result = new Dictionary<string, object>();

            foreach (var kvp in driveData)
            {
                string key = kvp.Key;
                object value = kvp.Value;

                if (dUIConfigData.ContainsKey(key) &&
                    dUIConfigData[key].TryGetValue("单位", out object unitObj) &&
                    unitObj is string unit &&
                    unit == "mm" &&
                    value is IConvertible)
                {
                    try
                    {
                        double numericValue = Convert.ToDouble(value);
                        result[key] = numericValue / 1000.0;
                    }
                    catch
                    {
                        // 如果无法转换为数字，保留原值
                        result[key] = value;
                    }
                }
                else
                {
                    result[key] = value;
                }
            }

            return result;
        } //工具
        public static Dictionary<string, Dictionary<string, object>> ExtractParamDict(
           Dictionary<string, Dictionary<string, object>> dUIConfigData)
        {
            var keysToKeep = new HashSet<string> { "最大值", "最小值", "单位", "输入列表", "默认值" };
            var paramDict = new Dictionary<string, Dictionary<string, object>>();

            foreach (var outerKvp in dUIConfigData)
            {
                var filteredInnerDict = new Dictionary<string, object>();

                foreach (var innerKvp in outerKvp.Value)
                {
                    if (keysToKeep.Contains(innerKvp.Key))
                    {
                        string newKey = innerKvp.Key == "输入列表" ? "可选值" : innerKvp.Key;
                        filteredInnerDict[newKey] = innerKvp.Value;
                    }
                }

                paramDict[outerKvp.Key] = filteredInnerDict;
            }

            return paramDict;
        }//工具
        //private string CreateWorkingPathByConfig(string zipFilePath)
        //{
        //    //string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(zipFilePath).Replace("_Config", "");  // 获取文件名（不含后缀）
        //    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(zipFilePath);
        //    string destinationFolderPath = Path.Combine(DataStore.Instance.sParentPath, $"_{fileNameWithoutExtension}");  // 解压后的文件夹路径
        //    if (Directory.Exists(destinationFolderPath))
        //    {
        //        Directory.Delete(destinationFolderPath, true);
        //    }
        //    //destinationFolderPath = GetUniqueFolderPath(destinationFolderPath);
        //    XmlHandler.ExtractZip(zipFilePath, destinationFolderPath);//创建文件夹，并且解压到目标文件夹
        //    //string modelFolder = Path.Combine(destinationFolderPath, "model");

        //    // 1. 删除路径 A 中的所有内容，除了 "model" 文件夹
        //    //DeleteExceptModel(destinationFolderPath);

        //    //// 2. 将 model 文件夹中的内容剪切到路径 A
        //    //MoveModelContentToRoot(modelFolder, destinationFolderPath);

        //    //// 3. 删除 model 文件夹
        //    //Directory.Delete(modelFolder, true);
        //    DataStore.Instance.sWorkingPath_New = destinationFolderPath;
        //    return destinationFolderPath;
        //}
        public string GetUniqueFolderPath(string originalPath)
        {
            if (!Directory.Exists(originalPath))
                return originalPath;

            int suffix = 1;
            string newPath;

            do
            {
                newPath = $"{originalPath}_{suffix}";
                suffix++;
            } while (Directory.Exists(newPath));

            return newPath;
        }
        public static List<SketchSpline> GetEquationCurvesFromSketch(Sketch sketch)
        {
            List<SketchSpline> equationCurves = new List<SketchSpline>();

            if (sketch == null)
                return equationCurves;

            object[] segments = sketch.GetSketchSegments() as object[];

            if (segments == null)
                return equationCurves;

            foreach (object obj in segments)
            {
                SketchSegment segment = obj as SketchSegment;
                if (segment == null) continue;

                int type = segment.GetType();

                if (type == (int)swSketchSegments_e.swSketchSPLINE) // 方程式曲线
                {
                    SketchSpline eqCurve = segment as SketchSpline;
                    if (eqCurve != null)
                    {
                        equationCurves.Add(eqCurve);
                    }
                }
            }

            return equationCurves;
        }//工具
        public int OnDocChange()
        {
            return 0;
        }
        public int OnDocLoad(string docTitle, string docPath)
        {
            return 0;
        }
        public int OnModelChange()
        {
            return 0;
        }
        public List<string> SplitStringByCustomSeparator(string sFullPath, string sSplit)
        {
            // 使用string.Split方法对字符串进行分割
            var splitResult = sFullPath.Split(new[] { sSplit }, StringSplitOptions.None);

            // 将结果转换为List<string>并返回
            return splitResult.ToList();
        }
        public static SketchSegment FindSketchSegmentByName(ModelDoc2 model, string targetSegmentName)
        {
            if (model == null || string.IsNullOrWhiteSpace(targetSegmentName))
                return null;

            Feature feature = model.FirstFeature();

            while (feature != null)
            {
                string typeName = feature.GetTypeName2();

                // 只遍历 Sketch 特征
                if (typeName == "ProfileFeature" || typeName == "Sketch")
                {
                    object specificFeat = feature.GetSpecificFeature2();
                    Sketch sketch = specificFeat as Sketch;
                    if (sketch != null)
                    {
                        object[] segments = sketch.GetSketchSegments() as object[];
                        if (segments != null)
                        {
                            foreach (object obj in segments)
                            {
                                SketchSegment seg = obj as SketchSegment;
                                if (seg != null && seg.GetName() == targetSegmentName)
                                {
                                    return seg;
                                }
                            }
                        }
                    }
                }

                feature = feature.GetNextFeature();
            }

            return null; // 没找到
        }
        public static Dictionary<string, string> ParseFormulaString(string formulaString)
        {
            var result = new Dictionary<string, string>();

            if (string.IsNullOrWhiteSpace(formulaString))
                return result;

            // 按 SpLine_Split 分割每一组
            string[] parts = formulaString.Split(new string[] { Defines.SpLine_Split }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string part in parts)
            {
                // 再按 "=" 分割变量名和公式内容
                int equalIndex = part.IndexOf('=');
                if (equalIndex > 0 && equalIndex < part.Length - 1)
                {
                    string key = part.Substring(0, equalIndex).Trim();
                    string value = part.Substring(equalIndex + 1).Trim();

                    if (!string.IsNullOrEmpty(key))
                    {
                        result[key] = value;
                    }
                }
            }

            return result;
        }//工具方法

        public string GetFullPath(string sElement)
        {
            var parentChildMap = DataStore.Instance.GetParentChildMap();

            List<string> path = new List<string> { sElement };


            while (parentChildMap.ContainsKey(sElement))
            {
                sElement = parentChildMap[sElement];
                if (sElement != null && sElement != "null")
                {
                    path.Insert(0, sElement);
                }
            }

            string sElementFullPath = string.Join(Defines.Comp_Split, path);
            return sElementFullPath;
        }//工具方法

        public static string EvaluateConditionExpressions(string input)
        {
            // 将输入字符串根据Quot_Split进行分割，得到表达式列表
            var expressions = input.Split(new[] { Defines.Quot_Split }, StringSplitOptions.RemoveEmptyEntries);
            string sTempResult = "allfalse";

            foreach (var expression in expressions)
            {
                // 去掉表达式中的单引号
                string cleanedExpression = expression.Replace("'", "");

                // 尝试根据IF_Split进行分割
                var ifSplit = cleanedExpression.Split(new[] { Defines.IF_Split }, StringSplitOptions.None);

                if (ifSplit.Length == 2)
                {
                    var conditionExpression = ifSplit[1].Trim();
                    var resultExpression = ifSplit[0].Trim();
                    var orSplit = conditionExpression.Split(new[] { Defines.Or_Split }, StringSplitOptions.None);

                    foreach (var orCond in orSplit)
                    {
                        var andSplit = orCond.Split(new[] { Defines.And_Split }, StringSplitOptions.None);
                        //var resultExpression = ifSplit[0].Trim();
                        bool isAllTrue = true;
                        foreach (var cond in andSplit)
                        {
                            string condResult = EvaluateExpression(cond.Trim()).ToString();
                            if (!(bool.TryParse(condResult, out bool isPass) && isPass))
                            {
                                isAllTrue = false;
                                break;
                            }
                        }

                        if (isAllTrue)
                        {
                            // 如果条件为真，计算结果表达式
                            var result = EvaluateExpression(resultExpression);
                            return result.ToString();
                        }
                        else
                        {
                            if (bool.TryParse(resultExpression, out bool boolResult))
                            {
                                bool notBoolResult = !boolResult;
                                sTempResult = notBoolResult.ToString();
                            }
                        }
                    }
                }
                else
                {
                    // 不存在条件，直接计算表达式
                    var result = EvaluateExpression(cleanedExpression);
                    return result.ToString();
                }
            }
            // 如果所有条件都为false，抛出异常
            Logger.Instance.Log("Error: All conditions evaluated to false.");
            return sTempResult;
        }//工具方法

        public static string EvaluateConditionExpressions_SPLine(string input)
        {
            var splines = input.Split(new[] { Defines.SpLine_Split }, StringSplitOptions.RemoveEmptyEntries);
            List<string> splineList = new List<string>();

            foreach (var spline in splines)
            {
                // 将输入字符串根据Quot_Split进行分割，得到表达式列表
                var expressions = spline.Split(new[] { Defines.Quot_Split }, StringSplitOptions.RemoveEmptyEntries);
                string sTempResult = "allfalse";

                foreach (var expression in expressions)
                {
                    // 去掉表达式中的单引号
                    string cleanedExpression = expression.Replace("'", "");

                    // 尝试根据IF_Split进行分割
                    var ifSplit = cleanedExpression.Split(new[] { Defines.IF_Split }, StringSplitOptions.None);

                    if (ifSplit.Length == 2)
                    {
                        // 存在条件表达式
                        var conditionExpression = ifSplit[1].Trim();
                        var resultExpression = ifSplit[0].Trim();

                        // 计算条件表达式

                        string conditionResult = EvaluateExpression(conditionExpression).ToString();
                        if (bool.TryParse(conditionResult, out bool isPass))
                        {
                            if (isPass)
                            {
                                // 如果条件为真，计算结果表达式
                                var result = EvaluateExpression(resultExpression, true);
                                splineList.Add(result.ToString());
                                break;
                                //return result.ToString();
                            }
                        }
                    }
                    else
                    {
                        // 不存在条件，直接计算表达式
                        var result = EvaluateExpression(cleanedExpression, true);
                        splineList.Add(result.ToString());
                        break;
                        //return result.ToString();
                    }
                }
            }
            string sFinalResult = string.Join(Defines.SpLine_Split, splineList);

            // 如果所有条件都为false，抛出异常
            //Logger.Instance.Log("Error: All conditions evaluated to false.");
            return sFinalResult;
        }//工具方法
        public static object EvaluateExpression(string expression, bool spline = false)
        {
            try
            {
                // 检查表达式中是否包含 '='，并且不是数学比较
                if (expression.Contains('=') && !expression.Contains(">=") && !expression.Contains("<=") && !expression.Contains("=="))
                {
                    if (spline)
                        return expression;

                    // 分割字符串，获取等号两边的值
                    var parts = expression.Split('=');
                    if (parts.Length == 2)
                    {
                        string leftValue = parts[0].Trim();
                        string rightValue = parts[1].Trim();

                        // 尝试将值转换为数字
                        bool isLeftNumeric = double.TryParse(leftValue, out double leftNumber);
                        bool isRightNumeric = double.TryParse(rightValue, out double rightNumber);

                        // 如果两边都不是数字，则直接比较字符串
                        if (!isLeftNumeric && !isRightNumeric)
                        {
                            return leftValue == rightValue;
                        }
                    }
                }

                // 如果是数字或数学表达式，使用表达式解析器处理
                expression = expression.Replace("÷", "/");
                Expression e = new Expression(expression);
                object result;
                try
                {
                    result = e.Evaluate();
                }
                catch (Exception ex)
                {
                    Logger.Instance.Log($"无法解析表达式: {ex.Message}");
                    result = expression;
                }


                if (result is bool boolResult)
                {
                    return boolResult;
                }
                else if (result is double || result is int)
                {
                    // 数值计算结果，非零为true
                    return Convert.ToDouble(result);
                }
                else if (result is string)
                {
                    return (string)result;
                }
                else
                {
                    throw new ArgumentException("无法解析表达式");
                }
            }
            catch (Exception ex)
            {
                throw new ArgumentException($"无法解析表达式: {ex.Message}");
            }
        }//工具方法
        public void UpdateEquation(IModelDoc2 oTargetDoc, string sName, string sValue)
        {
            // 获取 Equation Manager
            IEquationMgr equationMgr = oTargetDoc.GetEquationMgr();

            if (equationMgr == null)
            {
                throw new Exception("Failed to get EquationMgr.");
            }

            // 遍历方程式，找到名称为 sName 的方程式
            for (int i = 0; i < equationMgr.GetCount(); i++)
            {
                // 获取方程式的完整文本
                string equationText = equationMgr.Equation[i];

                // 方程式文本格式为 "名称" = "值"
                // 使用等号分割，获取名称
                string[] equationParts = equationText.Split('=');
                if (equationParts.Length > 1)
                {
                    string equationName = equationParts[0].Trim().Trim('"'); // 去除两端的空格和引号
                    if (equationName == sName)
                    {
                        // 修改方程式的值
                        string newEquation = $"\"{sName}\" = {sValue}";
                        equationMgr.Equation[i] = newEquation;
                        oTargetDoc.EditRebuild3();
                        return;
                    }
                }
            }

            throw new Exception($"Equation with name '{sName}' not found.");
        }//工具方法
        public Feature GetFeatureFromEdge(Edge swEdge)
        {
            if (swEdge == null)
            {
                throw new ArgumentNullException(nameof(swEdge), "Edge is null");
            }

            // 获取 Edge 所属的 Faces（可能属于多个 Face）
            object[] faceArray = (object[])swEdge.GetTwoAdjacentFaces2();
            if (faceArray == null || faceArray.Length == 0)
            {
                Logger.Instance.Log("Edge does not belong to any face.");
                return null;
            }

            // 遍历所有 Face，获取第一个有效的 Feature
            foreach (object faceObj in faceArray)
            {
                IFace2 swFace = faceObj as IFace2;
                if (swFace != null)
                {
                    // 获取生成此 Face 的 Feature
                    Feature swFeature = (Feature)swFace.GetFeature();
                    if (swFeature != null)
                    {
                        return swFeature;
                    }
                }
            }

            Logger.Instance.Log("No feature found for the given edge.");
            return null;
        }//工具方法
        public string GetTempName(string sElementName)
        {
            if (DataStore.Instance.dName_NoteData.TryGetValue(sElementName, out var sNote))
            {
                return (string)sNote;
            }
            else
            {
                return null;
            }
        }//工具方法（这个youyuu）
    }
}
